package com.sambo.inspection.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.sambo.inspection.InspectionApplication;
import com.sambo.inspection.R;
import com.sambo.inspection.activity.support.BaseActivity;
import com.sambo.inspection.bean.GlobleBean;
import com.sambo.inspection.bean.MessageBean;
import com.sambo.inspection.bean.UserInfo;
import com.sambo.inspection.component.TitlePopup;
import com.sambo.inspection.fragment.EventReportFragment;
import com.sambo.inspection.fragment.RoutingInspectionRecordFragment;
import com.sambo.inspection.fragment.RoutingInspectionTaskFragment;
import com.sambo.inspection.fragment.SummaryFragment;
import com.sambo.inspection.fragment.WorkOrderFragment;
import com.sambo.inspection.http.HttpClient;
import com.sambo.inspection.http.HttpResponseHandler;
import com.sambo.inspection.http.Urls;
import com.sambo.inspection.util.DateUtil;
import com.sambo.inspection.util.DeviceUtil;
import com.sambo.inspection.util.JsonUtil;
import com.sambo.inspection.util.LogUtil;
import com.sambo.inspection.util.SpUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    TextView tvUsername;
    ImageView ivMessage;
    TextView tvMessageCount;
    ImageView ivMenu;

    SummaryFragment mSummaryFragment;
    RoutingInspectionTaskFragment mRoutingInspectionTaskFragment;
    RoutingInspectionRecordFragment mRoutingInspectionRecordFragment;
    EventReportFragment mEventReportFragment;
    WorkOrderFragment mWorkOrderFragment;

    LinearLayout llSummary;
    ImageView ivSummaryImg;
    TextView tvSummaryText;

    LinearLayout llRoutingInspectionTask;
    ImageView ivRoutingInspectionTaskImg;
    TextView tvRoutingInspectionTaskText;

    LinearLayout llRoutingInspectionRecord;
    ImageView ivRoutingInspectionRecordImg;
    TextView tvRoutingInspectionRecordText;

    LinearLayout llEventReport;
    ImageView ivEventReportImg;
    TextView tvEventReportText;

    LinearLayout llWorkOrder;
    ImageView ivWorkOrderImg;
    TextView tvWorkOrderText;

    // Menu
    private TitlePopup titlePopup;

    private FragmentManager mFragmentManager;

    private long lastTime;

    private long lastMsgTS;

    private int newMessageCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InspectionApplication.setMainActivity(this);

        tvUsername = findViewById(R.id.tv_username);
        ivMessage = findViewById(R.id.iv_message);
        tvMessageCount = findViewById(R.id.tv_message_count);
        ivMenu = findViewById(R.id.iv_menu);
        llSummary = findViewById(R.id.ll_summary);
        ivSummaryImg = findViewById(R.id.iv_summary_img);
        tvSummaryText = findViewById(R.id.tv_summary_text);
        llRoutingInspectionTask = findViewById(R.id.ll_routing_inspection_task);
        ivRoutingInspectionTaskImg = findViewById(R.id.iv_routing_inspection_task_img);
        tvRoutingInspectionTaskText = findViewById(R.id.tv_routing_inspection_task_text);
        llRoutingInspectionRecord = findViewById(R.id.ll_routing_inspection_record);
        ivRoutingInspectionRecordImg = findViewById(R.id.iv_routing_inspection_record_img);
        tvRoutingInspectionRecordText = findViewById(R.id.tv_routing_inspection_record_text);
        llEventReport = findViewById(R.id.ll_event_report);
        ivEventReportImg = findViewById(R.id.iv_event_report_img);
        tvEventReportText = findViewById(R.id.tv_event_report_text);
        llWorkOrder = findViewById(R.id.ll_work_order);
        ivWorkOrderImg = findViewById(R.id.iv_work_order_img);
        tvWorkOrderText = findViewById(R.id.tv_work_order_text);

        titlePopup = new TitlePopup(this, DeviceUtil.dp2Px(130), ViewGroup.LayoutParams.WRAP_CONTENT);
        titlePopup.setItemOnClickListener(new TitlePopup.OnItemOnClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(MainActivity.this, InformationQueryActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(MainActivity.this, OptionActivity.class));
                        break;
                    default:
                        break;
                }
            }
        });

        ivMessage.setOnClickListener(this);
        ivMenu.setOnClickListener(this);
        llSummary.setOnClickListener(this);
        llRoutingInspectionTask.setOnClickListener(this);
        llRoutingInspectionRecord.setOnClickListener(this);
        llEventReport.setOnClickListener(this);
        llWorkOrder.setOnClickListener(this);

//        tvUsername.setText("管理员");
        tvMessageCount.setVisibility(View.GONE);

        mFragmentManager = getSupportFragmentManager();

        showSummary();

        lastMsgTS = SpUtil.getLastMessageTS(GlobleBean.getInstance().getUserName());

        InspectionApplication.getInstance().startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        InspectionApplication.setMainActivity(null);

        if (InspectionApplication.getInstance().isPushServiceRunning()) {
            InspectionApplication.getInstance().stopPushService();
        }

        if (InspectionApplication.getInstance().isLocationSetup()) {
            InspectionApplication.getInstance().stopLocation();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_message:
                Intent msgIntent = new Intent(this, MessageActivity.class);
                startActivity(msgIntent);
                break;
            case R.id.iv_menu:
                titlePopup.show(ivMenu);
                break;
            case R.id.ll_summary:
                showSummary();
                break;
            case R.id.ll_routing_inspection_task:
                showRoutingInspectionTask();
                break;
            case R.id.ll_routing_inspection_record:
                showRoutingInspectionRecord();
                break;
            case R.id.ll_event_report:
                showEventReport();
                break;
            case R.id.ll_work_order:
                showWorkOrder();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (System.currentTimeMillis() - lastTime > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    lastTime = System.currentTimeMillis();
                } else {
                    finish();
//                    System.exit(0);
                }

                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showSummary() {

        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mSummaryFragment == null) {
            mSummaryFragment = new SummaryFragment();
            transaction.add(R.id.fragment_content, mSummaryFragment);
        } else {
            transaction.show(mSummaryFragment);
        }

        if (mRoutingInspectionTaskFragment != null) {
            transaction.hide(mRoutingInspectionTaskFragment);
        }

        if (mRoutingInspectionRecordFragment != null) {
            transaction.hide(mRoutingInspectionRecordFragment);
        }

        if (mEventReportFragment != null) {
            transaction.hide(mEventReportFragment);
        }
        if (mWorkOrderFragment != null) {
            transaction.hide(mWorkOrderFragment);
        }

        transaction.commit();

        ivSummaryImg.setImageResource(R.mipmap.icon_tab_main_selected);
        tvSummaryText.setTextColor(getResources().getColor(R.color.weixin_green));
        ivRoutingInspectionTaskImg.setImageResource(R.mipmap.icon_tab_routing_inspection);
        tvRoutingInspectionTaskText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionRecordImg.setImageResource(R.mipmap.icon_tab_routing_inspection_record);
        tvRoutingInspectionRecordText.setTextColor(getResources().getColor(R.color.font_normal));
        ivEventReportImg.setImageResource(R.mipmap.icon_tab_event_report);
        tvEventReportText.setTextColor(getResources().getColor(R.color.font_normal));
        ivWorkOrderImg.setImageResource(R.mipmap.icon_tab_work_order);
        tvWorkOrderText.setTextColor(getResources().getColor(R.color.font_normal));

    }

    public void showRoutingInspectionTask() {

        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mRoutingInspectionTaskFragment == null) {
            mRoutingInspectionTaskFragment = new RoutingInspectionTaskFragment();
            transaction.add(R.id.fragment_content, mRoutingInspectionTaskFragment);
        } else {
            transaction.show(mRoutingInspectionTaskFragment);
        }

        if (mSummaryFragment != null) {
            transaction.hide(mSummaryFragment);
        }

        if (mRoutingInspectionRecordFragment != null) {
            transaction.hide(mRoutingInspectionRecordFragment);
        }

        if (mEventReportFragment != null) {
            transaction.hide(mEventReportFragment);
        }

        if (mWorkOrderFragment != null) {
            transaction.hide(mWorkOrderFragment);
        }

        transaction.commit();

        ivSummaryImg.setImageResource(R.mipmap.icon_tab_main);
        tvSummaryText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionTaskImg.setImageResource(R.mipmap.icon_tab_routing_inspection_selected);
        tvRoutingInspectionTaskText.setTextColor(getResources().getColor(R.color.weixin_green));
        ivRoutingInspectionRecordImg.setImageResource(R.mipmap.icon_tab_routing_inspection_record);
        tvRoutingInspectionRecordText.setTextColor(getResources().getColor(R.color.font_normal));
        ivEventReportImg.setImageResource(R.mipmap.icon_tab_event_report);
        tvEventReportText.setTextColor(getResources().getColor(R.color.font_normal));
        ivWorkOrderImg.setImageResource(R.mipmap.icon_tab_work_order);
        tvWorkOrderText.setTextColor(getResources().getColor(R.color.font_normal));
    }

    public void showRoutingInspectionRecord() {

        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mRoutingInspectionRecordFragment == null) {
            mRoutingInspectionRecordFragment = new RoutingInspectionRecordFragment();
            transaction.add(R.id.fragment_content, mRoutingInspectionRecordFragment);
        } else {
            transaction.show(mRoutingInspectionRecordFragment);
        }

        if (mSummaryFragment != null) {
            transaction.hide(mSummaryFragment);
        }

        if (mRoutingInspectionTaskFragment != null) {
            transaction.hide(mRoutingInspectionTaskFragment);
        }

        if (mEventReportFragment != null) {
            transaction.hide(mEventReportFragment);
        }

        if (mWorkOrderFragment != null) {
            transaction.hide(mWorkOrderFragment);
        }

        transaction.commit();

        ivSummaryImg.setImageResource(R.mipmap.icon_tab_main);
        tvSummaryText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionTaskImg.setImageResource(R.mipmap.icon_tab_routing_inspection);
        tvRoutingInspectionTaskText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionRecordImg.setImageResource(R.mipmap.icon_tab_routing_inspection_record_selected);
        tvRoutingInspectionRecordText.setTextColor(getResources().getColor(R.color.weixin_green));
        ivEventReportImg.setImageResource(R.mipmap.icon_tab_event_report);
        tvEventReportText.setTextColor(getResources().getColor(R.color.font_normal));
        ivWorkOrderImg.setImageResource(R.mipmap.icon_tab_work_order);
        tvWorkOrderText.setTextColor(getResources().getColor(R.color.font_normal));
    }

    public void showEventReport() {

        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mEventReportFragment == null) {
            mEventReportFragment = new EventReportFragment();
            transaction.add(R.id.fragment_content, mEventReportFragment);
        } else {
            transaction.show(mEventReportFragment);
        }

        if (mSummaryFragment != null) {
            transaction.hide(mSummaryFragment);
        }

        if (mRoutingInspectionTaskFragment != null) {
            transaction.hide(mRoutingInspectionTaskFragment);
        }

        if (mRoutingInspectionRecordFragment != null) {
            transaction.hide(mRoutingInspectionRecordFragment);
        }

        if (mWorkOrderFragment != null) {
            transaction.hide(mWorkOrderFragment);
        }

        transaction.commit();

        ivSummaryImg.setImageResource(R.mipmap.icon_tab_main);
        tvSummaryText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionTaskImg.setImageResource(R.mipmap.icon_tab_routing_inspection);
        tvRoutingInspectionTaskText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionRecordImg.setImageResource(R.mipmap.icon_tab_routing_inspection_record);
        tvRoutingInspectionRecordText.setTextColor(getResources().getColor(R.color.font_normal));
        ivEventReportImg.setImageResource(R.mipmap.icon_tab_event_report_selected);
        tvEventReportText.setTextColor(getResources().getColor(R.color.weixin_green));
        ivWorkOrderImg.setImageResource(R.mipmap.icon_tab_work_order);
        tvWorkOrderText.setTextColor(getResources().getColor(R.color.font_normal));
    }

    public void showWorkOrder() {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mWorkOrderFragment == null) {
            mWorkOrderFragment = new WorkOrderFragment();
            transaction.add(R.id.fragment_content, mWorkOrderFragment);
        } else {
            transaction.show(mWorkOrderFragment);
        }

        if (mSummaryFragment != null) {
            transaction.hide(mSummaryFragment);
        }

        if (mRoutingInspectionTaskFragment != null) {
            transaction.hide(mRoutingInspectionTaskFragment);
        }

        if (mRoutingInspectionRecordFragment != null) {
            transaction.hide(mRoutingInspectionRecordFragment);
        }

        if (mEventReportFragment != null) {
            transaction.hide(mEventReportFragment);
        }

        transaction.commit();
        ivSummaryImg.setImageResource(R.mipmap.icon_tab_main);
        tvSummaryText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionTaskImg.setImageResource(R.mipmap.icon_tab_routing_inspection);
        tvRoutingInspectionTaskText.setTextColor(getResources().getColor(R.color.font_normal));
        ivRoutingInspectionRecordImg.setImageResource(R.mipmap.icon_tab_routing_inspection_record);
        tvRoutingInspectionRecordText.setTextColor(getResources().getColor(R.color.font_normal));
        ivEventReportImg.setImageResource(R.mipmap.icon_tab_event_report);
        tvEventReportText.setTextColor(getResources().getColor(R.color.font_normal));
        ivWorkOrderImg.setImageResource(R.mipmap.icon_tab_work_order_selected);
        tvWorkOrderText.setTextColor(getResources().getColor(R.color.weixin_green));
    }

    public void refreshMessageList() {
        getMessageList();
    }

    private void getMessageList() {

        Map<String, String> params = new HashMap<>();

        params.put("state", "2");
        params.put("page", "1");
        params.put("limit", "100");

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.GET_MESSAGE, params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        MessageBean[] response = JsonUtil.toObj(value.toString(), MessageBean[].class);

                        newMessageCount = 0;

                        if (response != null && response.length > 0) {

                            if (mSummaryFragment != null) {
                                mSummaryFragment.setLastMessage(response[0].getTitle());
                            }

                            for (MessageBean bean : response) {
                                if (DateUtil.dateTime2TS(bean.getCreateDate()) > lastMsgTS) {
                                    newMessageCount++;
                                }
                            }

                            if (newMessageCount > 99) {
                                newMessageCount = 99;
                            }
                        }

                        if (newMessageCount == 0) {
                            tvMessageCount.setVisibility(View.GONE);
                        } else {
                            tvMessageCount.setVisibility(View.VISIBLE);
                            tvMessageCount.setText(String.valueOf(newMessageCount));
                        }
                    }

                    @Override
                    public void onInnovationFailure(String msg) {
                        super.onInnovationFailure(msg);
                    }
                }, null);
    }

    private void getUserInfo() {

        Map<String, String> params = new HashMap<>();
        params.put("access_token", GlobleBean.getInstance().getAccessToken());

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.GET_USER_INFO + GlobleBean.getInstance().getUserName(), params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        UserInfo response = JsonUtil.toObj(value.toString(), UserInfo.class);

                        if (response != null) {

                            GlobleBean.getInstance().setUserID(response.getId());
                            GlobleBean.getInstance().setNickName(response.getRealName());
                            GlobleBean.getInstance().setPhone(response.getTel());
                            GlobleBean.getInstance().setMail(response.getMail());
                            GlobleBean.getInstance().setDeptID(response.getDept().getDeptId());

                            tvUsername.setText(response.getRealName());

                        }

                    }

                    @Override
                    public void onInnovationFailure(String msg) {
                        super.onInnovationFailure(msg);
                    }
                }, null);
    }

    /*************************************** 权限检查******************************************************/

    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    @Override
    protected void onResume() {
        super.onResume();
        // 获取用户信息
        getUserInfo();
        // 获取通知消息
        lastMsgTS = SpUtil.getLastMessageTS(GlobleBean.getInstance().getUserName());
        getMessageList();

        if (!InspectionApplication.getInstance().isPushServiceRunning()) {
            InspectionApplication.getInstance().startPushService();
        }

        try{
            if (Build.VERSION.SDK_INT >= 23) {
                if (isNeedCheck) {
                    checkPermissions(needPermissions);
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @since 2.5.0
     */
    @TargetApi(23)
    private void checkPermissions(String... permissions) {
        try{
            if (Build.VERSION.SDK_INT >= 23 && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    try {
                        String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                        Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class, int.class});
                        method.invoke(this, array, 0);
                    } catch (Throwable e) {

                    }
                }
            }

        }catch(Throwable e){
            e.printStackTrace();
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    @TargetApi(23)
    private List<String> findDeniedPermissions(String[] permissions) {
        try{
            List<String> needRequestPermissonList = new ArrayList<String>();
            if (Build.VERSION.SDK_INT >= 23 && getApplicationInfo().targetSdkVersion >= 23) {
                for (String perm : permissions) {
                    if (checkMySelfPermission(perm) != PackageManager.PERMISSION_GRANTED
                            || shouldShowMyRequestPermissionRationale(perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            }
            return needRequestPermissonList;
        }catch(Throwable e){
            e.printStackTrace();
        }
        return null;
    }

    private int checkMySelfPermission(String perm) {
        try {
            Method method = getClass().getMethod("checkSelfPermission", new Class[]{String.class});
            Integer permissionInt = (Integer) method.invoke(this, perm);
            return permissionInt;
        } catch (Throwable e) {
        }
        return -1;
    }

    private boolean shouldShowMyRequestPermissionRationale(String perm) {
        try {
            Method method = getClass().getMethod("shouldShowRequestPermissionRationale", new Class[]{String.class});
            Boolean permissionInt = (Boolean) method.invoke(this, perm);
            return permissionInt;
        } catch (Throwable e) {
        }
        return false;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        try{
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
        return true;
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        try{
            if (Build.VERSION.SDK_INT >= 23) {
                if (requestCode == PERMISSON_REQUESTCODE) {
                    if (!verifyPermissions(paramArrayOfInt)) {
                        showMissingPermissionDialog();
                        isNeedCheck = false;
                    }
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        try{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("当前应用缺少必要权限。\\n\\n请点击\\\"设置\\\"-\\\"权限\\\"-打开所需权限");

            // 拒绝, 退出应用
            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try{
                                finish();
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                        }
                    });

            builder.setPositiveButton("设置",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                startAppSettings();
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                        }
                    });

            builder.setCancelable(false);

            builder.show();
        }catch(Throwable e){
            e.printStackTrace();
        }
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        try{
            Intent intent = new Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
